package com.wealth.cart.service.impl;

import iaas.service.impl.BaseServiceImpl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.wealth.cart.entity.Cart;
import com.wealth.cart.entity.CartGoodsInfo;
import com.wealth.cart.entity.CartItem;
import com.wealth.cart.enums.CartStatusEnum;
import com.wealth.cart.repository.CartDao;
import com.wealth.cart.repository.CartItemDao;
import com.wealth.cart.service.ICartItemService;
@Component
public class CartItemServiceImpl  extends BaseServiceImpl<CartItem> implements ICartItemService {

	@PersistenceContext
 	private EntityManager em;
	
	
    @Autowired
    CartDao cartDao;
    
    @Autowired
    CartItemDao cartItemDao;
 
	@SuppressWarnings("unchecked")
	@Override
	public List<CartItem> getCartByCartId(long cartId) throws Exception {
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT DISTINCT * FROM `t_cart_item`  WHERE cart_id = ");
	    sql.append(cartId + " AND STATUS > 0   GROUP BY merchant_id  ");
		Query query = em.createNativeQuery(sql.toString(), CartItem.class);
		List<CartItem> list = (List<CartItem>) query.getResultList();
		return list;
	}

	@Override
	public List<CartItem> findCartItemByCartId(Long memberId, long marketId,
			Integer status) {
		
		Cart cart = cartDao.findCartByMemberIdAndMarketId(memberId, marketId);
		
		List<CartItem> list = cartItemDao.findCartItemByCartIdAndStatus(cart.getId(),status);
		
		return list;
	}

	
	//订单支付成功后，删除购物车中的商品
	@Override
	public void delCartItem(Long memberId, Long marketId) throws Exception {
		//获取购物车
		Cart cart = cartDao.findCartByMemberIdAndMarketId(memberId, marketId);
		//遍历购物车明细
		if(cart.getCartItems().size()>0){
			for (CartItem item  : cart.getCartItems()) {
				//选中状态
				if(item.getStatus()==2){
					cartItemDao.delete(item);
				}
			}
		}
	}

	@Override
	public List<CartItem> getCheckCarItem(long cartId) throws Exception {
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT DISTINCT * FROM `t_cart_item`  WHERE cart_id = ");
	    sql.append(cartId + " AND STATUS = 2   GROUP BY merchant_id  ");
		Query query = em.createNativeQuery(sql.toString(), CartItem.class);
		List<CartItem> list = (List<CartItem>) query.getResultList();
		return list;	
	}

 
	
}
